﻿namespace AjLogo.Language
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class ListValue
    {
        public ListValue(object first, object rest)
        {
            this.First = first;
            this.Rest = rest;
        }

        public object First { get; set; }

        public object Rest { get; set; }

        public static ListValue MakeList(IEnumerable elements)
        {
            Stack stack = new Stack();

            foreach (object element in elements)
                stack.Push(element);

            ListValue list = null;

            while (stack.Count > 0)
            {
                list = new ListValue(stack.Pop(), list);
            }

            return list;
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");

            if (this.First != null)
                sb.Append(this.First.ToString());

            object rest = this.Rest;

            while (rest != null && rest is ListValue)
            {
                ListValue list = (ListValue) rest;

                sb.Append(" ");
                sb.Append(list.First.ToString());

                rest = list.Rest;
            }

            if (rest != null) 
            {
                sb.Append(".");
                sb.Append(rest.ToString());
            }

            sb.Append("]");

            return sb.ToString();
        }
    }
}
